$('.forgotBtn').on('click', function () {
    $('#forgot').toggleClass('toggle')
})
$('.registerBtn').on('click', function () {
    $('#register, #formContainer').toggleClass('toggle')
})
let loginName = $('#loginName')
let loginPass = $('#loginPass')

function inputCheck() {
    if (loginName.val().trim() === '') {
        sa.error('用户名不能为空')
        loginName.focus()
        return false
    }
    if (loginPass.val().trim() === '') {
        sa.error('密码不能为空')
        loginPass.focus()
        return false
    }
    return true
}

let PATH = '/main'

function login(captchaId) {
    sa.ajax(PATH + '/login', {}, (res1) => {
        sa.ajax(PATH + '/login', {
            key: loginName.val(),
            passwd: aesEncode(loginPass.val(), res1.data),
            captchaId: captchaId
        }, function (res) {
            // 登录获取并写入token
            localStorage.setItem('token', JSON.stringify(res.data.token))
            // 跳转页面
            sa.alert(res.msg, () => {
                if (parent === window) {
                    window.open("index.html", '_self')
                } else {
                    sa.closeCurrIframe();
                    parent.location.reload();
                }
            })
        }, {msg: '正在登录.....', sleep: 300})
    }, {msg: null, type: 'get'})
}

const config = {
    // 生成接口
    requestCaptchaDataUrl: sa.cfg.api_url + "/main/captcha?type=RANDOM",
    // 验证接口
    validCaptchaUrl: sa.cfg.api_url + "/main/captchaCheck",
    // 验证码绑定的div块
    bindEl: "#captcha-box",
    // 验证成功回调函数
    validSuccess: (res, c, tac) => {
        // 销毁验证码服务
        tac.destroyWindow();
        login(res.data.id);
    }
}
const style = {
    // 配置样式， logoURL地址
    logoUrl: "static/img/logo2.png"
}

function openCaptcha(type) {
    config.requestCaptchaDataUrl = "gen?type=" + type
}

$('#subLogin').on('click', function () {
    if (!inputCheck()) {
        return;
    }
    window.initTAC('static/plugins/tac', config, style)
        .then((tac) => {
            tac.init(); // 调用init则显示验证码
        })
        .catch((e) => {
            console.log('初始化tac失败', e);
        });
    ;
})

function getAvatar() {
    sa.ajax(PATH + '/avatar', {key: loginName.val()}, (res) => {
        if (res.data) {
            $('#avatar').attr('src', sa.getImgPath(res.data))
        } else {
            sa.msgWarn('加载头像失败，使用默认头像')
            $('#avatar').attr('src', 'static/plugins/login/images/avatar.png')
        }

    }, {type: 'get', msg: null})
}

loginName.on('change', () => {
    if (loginName.val()) {
        getAvatar();
    }
})
// 初始默认用户名以及密码
loginName.val('001')
loginPass.val('000000')
// 加载头像
getAvatar();
